package com.steven.ourcontest.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.os.CountDownTimer
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatButton
import com.steven.ourcontest.R

class TimeKeeperButton(context: Context,attrs: AttributeSet?) : AppCompatButton(context, attrs) {
    private var period = 0
    private var content: String? = null
    private var isRunning = false

    fun initKeeper(period: Int, content: String?) {
        this.content = content
        this.period = period
        isRunning = false
    }

    fun start(then:(()->Unit)?) {
        if (!isRunning) {
            isRunning = true
            isClickable = false
            then?.invoke()
            object : CountDownTimer(period.toLong(), 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    text = "${millisUntilFinished / 1000}$content"
                }

                override fun onFinish() {
                    destroy()
                }
            }.start()
        }
    }

    fun destroy() {
        isClickable = true
        isRunning = false
        text = "获取验证码"
        setBackgroundResource(R.drawable.shape_left_frame)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
    }
}